package com.etop.bank.utils;

import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Environment;
import android.text.format.Time;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;

/**
 * 写入拍照图像
 */
public class StreamUtil {

	/**
	 * 证卡类保存框内裁切图
	 *
	 * @param data
	 * @param saveImgPath
	 * @param tag
	 * @return
	 */
	public String saveCropBitmapFile(byte[] data, String saveImgPath, String tag) {

		BufferedOutputStream bos = null;
		Bitmap bitmap = null;
		String path = "";
		try {
			// 获得图片
			bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
			int pic_width = bitmap.getWidth();//1280
			int pic_height = bitmap.getHeight();//720
			//裁切图的宽高
			int height = (int) (pic_height * 0.8);//屏幕宽的0.8,拍照取景框的宽为屏幕的0.8
			int width = (int) (pic_height * 1.25);
			bitmap = Bitmap.createBitmap(bitmap, (int) (pic_width * 0.12), (int) (pic_height * 0.1), width, height,
					new Matrix(), false);
			File file = new File(saveImgPath, pictureName(tag));
			path = file.toString();
			if (!file.exists()) {
				file.createNewFile();
			}
			bos = new BufferedOutputStream(new FileOutputStream(file));
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bos.flush();//输出
				bos.close();//关闭
				bitmap.recycle();// 回收bitmap空间
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return path;
	}

	/**
	 * 返回一个文件命名
	 *
	 * @param tag
	 * @return
	 */
	public static String pictureName(String tag) {
		String str = tag + "_";
		StringBuilder sb = new StringBuilder();
		sb.append(str);
		Time time = new Time();
		time.setToNow(); // 取得系统时间。
		sb.append(time.year);
		int month = time.month + 1;
		int date = time.monthDay;
		if (month < 10) {
			sb.append("0" + month);
		} else {
			sb.append(month);
		}
		if (date < 10) {
			sb.append("0" + date + "_" + getFourRandom());
		} else {
			sb.append(date + "_" + getFourRandom());
		}
		sb.append(".jpg");
		return sb.toString();
	}

	/**
	 * 将原图片存储进SD卡
	 *
	 * @param bitmap   bitmap
	 * @param filePath 图像文件路径
	 * @param tag      文件命名开头标志
	 */
	public String saveBitmapFile(Bitmap bitmap, String filePath, String tag) {
		BufferedOutputStream bos = null;
		String path = "";
		try {
			File file = new File(filePath, pictureName(tag));
			file.createNewFile();
			path = file.toString();
			bos = new BufferedOutputStream(new FileOutputStream(file));
			//参2 ： 保存图像质量
			bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
			bos.flush();
			bos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return path;
	}

	/**
	 * 产生4位随机数(0000-9999)
	 *
	 * @return 4位随机数
	 */
	public static String getFourRandom() {
		Random random = new Random();
		String fourRandom = random.nextInt(10000) + "";
		int randLength = fourRandom.length();
		if (randLength < 4) {
			for (int i = 1; i <= 4 - randLength; i++)
				fourRandom = "0" + fourRandom;
		}
		return fourRandom;
	}

	/**
	 * 将授权文件从assets目录下获取，并且保存到data/data/包名 目录下
	 *
	 * @param context
	 */
	public static void initLicenseFile(Activity context, String licenseId) {
		//写入到内置存储应用包名缓存目录下
		File targetFile = new File(context.getCacheDir(), licenseId);
		if (targetFile.exists()) targetFile.delete();
		InputStream myInput = null;
		OutputStream myOutput = null;
		try {
			AssetManager assetManager = context.getAssets();

			myInput = assetManager.open(licenseId);
			myOutput = new FileOutputStream(targetFile);
			byte[] buffer = new byte[1024];
			int length;
			while ((length = myInput.read(buffer)) > 0) {
				myOutput.write(buffer, 0, length);
			}
			myOutput.flush();
			myOutput.close();
			myInput.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void initNCFile(Activity context, String ncName) {
		//写入到内置存储应用包名缓存目录下
		File targetFile = new File(context.getFilesDir(), ncName);
		InputStream myInput = null;
		OutputStream myOutput = null;
		try {
			AssetManager assetManager = context.getAssets();
			myInput = assetManager.open(ncName);
			myOutput = new FileOutputStream(targetFile);
			byte[] buffer = new byte[1024];
			int length;
			while ((length = myInput.read(buffer)) > 0) {
				myOutput.write(buffer, 0, length);
			}
			myOutput.flush();
			myOutput.close();
			myInput.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 保存byte[]数组
	 */
	/**
	 * 根据byte数组生成文件
	 *
	 * @param bytes 生成文件用到的byte数组
	 */
	public static void createFileWithByte(byte[] bytes) {
		// TODO Auto-generated method stub
		/**
		 * 创建File对象，其中包含文件所在的目录以及文件的命名
		 */
		File file = new File(Environment.getExternalStorageDirectory(),
				"idcard_img_byte.txt");
		// 创建FileOutputStream对象
		FileOutputStream outputStream = null;
		// 创建BufferedOutputStream对象
		BufferedOutputStream bufferedOutputStream = null;
		try {
			// 如果文件存在则删除
			if (file.exists()) {
				file.delete();
			}
			// 在文件系统中根据路径创建一个新的空文件
			file.createNewFile();
			// 获取FileOutputStream对象
			outputStream = new FileOutputStream(file);
			// 获取BufferedOutputStream对象
			bufferedOutputStream = new BufferedOutputStream(outputStream);
			// 往文件所在的缓冲输出流中写byte数据
			bufferedOutputStream.write(bytes);
			// 刷出缓冲输出流，该步很关键，要是不执行flush()方法，那么文件的内容是空的。
			bufferedOutputStream.flush();
		} catch (Exception e) {
			// 打印异常信息
			e.printStackTrace();
		} finally {
			// 关闭创建的流对象
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bufferedOutputStream != null) {
				try {
					bufferedOutputStream.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
	}

	/**
	 * 这里的算法是以短边压缩到1000~2000之间为目标，通过计算到1000的比值，然后需要将采样率控制为2的倍数
	 * 所以需要使用方法{@link #calInSampleSize(int)}进行计算
	 *
	 * @return 采样率
	 */
	public static int computeSize(int srcWidth, int srcHeight) {
		srcWidth = srcWidth % 2 == 1 ? srcWidth + 1 : srcWidth;
		srcHeight = srcHeight % 2 == 1 ? srcHeight + 1 : srcHeight;

		int shortSide = Math.min(srcWidth, srcHeight);

		int rate = (int) Math.floor(shortSide / 1000.0);

		return calInSampleSize(rate);
	}

	/**
	 * 通过移位操作计算采样率，是某个整数对应的二进制数保留最高位为1，其他位置为0的结果
	 *
	 * @param rate 比例
	 * @return 采样率
	 */
	private static int calInSampleSize(int rate) {
		int i = 0;
		while ((rate >> (++i)) != 0) ;
		return 1 << --i;
	}

	/**
	 * 根据路径获得图片并压缩，返回bitmap
	 *
	 * @param filePath filePath
	 * @return Bitmap
	 */
	public static Bitmap getSmallBitmap(String filePath, int srcWidth, int srcHeight) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);
		// Calculate inSampleSize
//        options.inSampleSize = computeSize(srcWidth, srcHeight);
		options.inSampleSize = 2;
		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;

		return BitmapFactory.decodeFile(filePath, options);
	}

	/**
	 * 旋转bitmap
	 * @param bm
	 * @param orientationDegree
	 * @return
	 */
	public static Bitmap BitmapRotation(Bitmap bm, final int orientationDegree) {
		Matrix m = new Matrix();
		m.setRotate(orientationDegree, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
		float targetX, targetY;
		if (orientationDegree == 90) {
			targetX = bm.getHeight();
			targetY = 0;
		} else {
			targetX = bm.getHeight();
			targetY = bm.getWidth();
		}

		final float[] values = new float[9];
		m.getValues(values);

		float x1 = values[Matrix.MTRANS_X];
		float y1 = values[Matrix.MTRANS_Y];

		m.postTranslate(targetX - x1, targetY - y1);

		Bitmap bm1 = Bitmap.createBitmap(bm.getHeight(), bm.getWidth(), Bitmap.Config.ARGB_8888);
		Paint paint = new Paint();
		Canvas canvas = new Canvas(bm1);
		canvas.drawBitmap(bm, m, paint);


		return bm1;
	}

	/**
	 * 读取文件中byte[]
	 */
	private byte[] readFile() {
		File file = new File(Environment.getExternalStorageDirectory(),
				"idcard_img_byte.txt");
		// 需要读取的文件，参数是文件的路径名加文件名
		if (file.isFile()) {
			// 以字节流方法读取文件
			FileInputStream fis = null;
			try {
				fis = new FileInputStream(file);
				// 设置一个，每次 装载信息的容器
				byte[] buffer = new byte[1024];
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
				// 开始读取数据
				int len = 0;// 每次读取到的数据的长度
				while ((len = fis.read(buffer)) != -1) {// len值为-1时，表示没有数据了
					// append方法往sb对象里面添加数据
					outputStream.write(buffer, 0, len);
				}
				// 输出字符串
				return outputStream.toByteArray();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("文件不存在！");
		}
		return null;
	}

}
